#include "wechatclientwidget.h"
#include "ui_wechatclientwidget.h"

WechatClientWidget::WechatClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::WechatClientWidget)
{
    ui->setupUi(this);
    setWindowTitle("WechatClient:8888");
    udpsocket = new QUdpSocket(this);
    initWechatClient();
}

WechatClientWidget::~WechatClientWidget()
{
    udpsocket->abort();
    delete ui;
}

void WechatClientWidget::initWechatClient()
{
     bool result = udpsocket->bind(QHostAddress::AnyIPv4, currentPort);
     if(result) {
         ALOG<<"服务绑定成功！";
     }
//    connect(ui->buttonsend, &QPushButton::clicked, this, &WechatClientWidget::on_buttonsend_clicked);
    connect(udpsocket,&QUdpSocket::readyRead,[=](){
            //没有可读的数据就返回
            if(!udpsocket->hasPendingDatagrams() || udpsocket->pendingDatagramSize()<=0)
                return;
            //注意收发两端文本要使用对应的编解码
            QNetworkDatagram recv_datagram=udpsocket->receiveDatagram();
            const QString recv_text=QString::fromUtf8(recv_datagram.data());
            ui->textEditrrecv->append(QString("[%1:%2 %3]")
                                 .arg(recv_datagram.senderAddress().toString())
                                 .arg(recv_datagram.senderPort())
                                 .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")));
            ui->textEditrrecv->append(recv_text);
        });


}

void WechatClientWidget::on_buttonsend_clicked()
{
    const int clientPort = ui->textEditport->toPlainText().toInt();
    const QString ipAddress = ui->textEditIp->toPlainText();
    ALOG<<"port:"<<clientPort<<",ip:"<<ipAddress;
    const QByteArray send_data=ui->textEditrsend->toPlainText().toUtf8();
    if(!udpsocket->isValid()) { //isValid表示准备好写
      initWechatClient();
       if(!udpsocket->isValid()) {
           ALOG<<"服务绑定成功！";
       } else {
           return;
       }
    }
    if(send_data.isEmpty()) {
        return;
    }
    const QHostAddress address=QHostAddress(ipAddress);
    qint64 ret = udpsocket->writeDatagram(QNetworkDatagram(send_data,address,clientPort));
    ui->textEditrsend->setText("");
    ALOG<<"发送消息:"<<ret;
}

void WechatClientWidget::on_buttonclose_clicked()
{
    ALOG<<"关闭连接";
    udpsocket->disconnectFromHost();
}
